package org.example;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class MyClass {

    private static final String classname = "myClass";

    public MyClass() {};

    @InitMethod
    public void init() {
        System.out.println("Init方法被调用");
    }

    //获取属性文件中的类

    public void getInputStream(){
        try{
            InputStream inputStream = new FileInputStream("src/main/resources/myapp.properties");
            try{
                Properties properties = new Properties();
                properties.load(inputStream);
                String clas = properties.getProperty(classname);
                if (clas == null) {
                    System.out.println("在属性文件中没有设置Class");
                }
                else{
                    try {
                        getInitMethod(clas);
                    } catch (ClassNotFoundException e) {
                        System.out.println("属性中标注的类不存在");
                    }
                }
            }catch (IOException e){
                System.out.println("属性文件不存在");
            }
        } catch (FileNotFoundException e) {
            System.out.println("路径错误");
        }
    }

    //获取类中被注解的方法

    public void  getInitMethod(String classname) throws ClassNotFoundException{

            for (Method method : Class.forName(classname).getDeclaredMethods()) {
                if (!method.isAnnotationPresent(InitMethod.class)) {
                    continue;
                }
                if (method.getParameterCount() > 0) {
                    System.out.println("带参数的方法不允许标注@InitMethod");
                }
                try{
                    method.invoke(Class.forName(classname).newInstance());
                }catch(InstantiationException | IllegalAccessException | InvocationTargetException e){

                }
                System.out.println(method);
                return;
            }
                System.out.println("没有方法标注@InitMethod");
    }
}